<template>
  <div style="padding: 20px">
    <div>
      <el-input placeholder="关键词搜索" v-model="keyword" style="width: 240px;">
        <el-button slot="append" icon="el-icon-search" @click="searchNew"></el-button>
      </el-input>
      <el-button icon="el-icon-refresh" circle @click="refreshNew" style="width: 40px; margin-left: 8px"
        type="success"></el-button>
      <el-button type="primary" @click="handleAdd">新增新闻</el-button>
    </div>
    <el-table :data="NewList" style="width: 100%; border-radius: 10px; margin-top: 8px" stripe v-loading="loading">
      <el-table-column type="index" :index="indexMethod" label="序号" width="75" align="center">
      </el-table-column>
      <el-table-column prop="title" label="标题" width="180" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column label="作者" width="160" align="center">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <img :src="scope.row.avatar" style="width: 38px; height: 38px; border-radius: 50%" />
            <span style="padding-left: 4px">{{ scope.row.nickname }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容" width="180" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="cover" label="封面" width="180" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          <el-image style="height: 100px" :src="scope.row.cover" :preview-src-list="[scope.row.cover]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" sortable prop="status" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 2" type="success">审核通过</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="danger">违规</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="warning">待审核</el-tag>
          <el-tag v-else type="info">存稿</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="类型名称" width="100" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" width="180"> </el-table-column>
      <el-table-column prop="publishTime" label="更新时间" align="center" width="180"> </el-table-column>
      <el-table-column label="操作" fixed="right" width="220">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="发布" placement="top">
            <el-button type="success" v-if="scope.row.status === 0" icon="el-icon-s-promotion" circle
              @click="publishNew(scope.row)" style="width: 40px"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="通过" placement="top">
            <el-button type="success" v-if="scope.row.status === 1 || scope.row.status === 3" icon="el-icon-success"
              circle @click="passNew(scope.row.id)" style="width: 40px"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="违规" placement="top">
            <el-button type="warning" v-if="scope.row.status === 1 || scope.row.status === 2" icon="el-icon-error" circle
              @click="failedNew(scope.row.id)" style="width: 40px"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="编辑" placement="top">
            <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"
              style="width: 40px"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button type="danger" icon="el-icon-delete" circle style="width: 40px"
              @click="deleteNew(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <div style="width: 40px; margin-top: 8px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="paramsForm.pageNum" :page-sizes="[10, 20, 30, 50]" :page-size="paramsForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" title="修改新闻" width="68%" top="4vh">
      <el-form :model="updateNewForm" :rules="rules" ref="updateNewForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="updateNewForm.title" placeholder="请输入新闻名称"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <v-md-editor v-model="updateNewForm.content" height="400px" :disabled-menus="[]"
            @upload-image="handleUploadImage"></v-md-editor>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload class="image-uploader" action="/api/upload/image" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="updateNewForm.cover" :src="updateNewForm.cover" class="image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="updateNewForm.type" placeholder="请选择">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false" style="width: 68px" size="medium">取消</el-button>
        <el-button type="primary" @click="updateOneNew('updateNewForm')" style="width: 68px" size="medium">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="addDialogVisible" title="修改新闻" width="68%" top="4vh">
      <el-form :model="addNewForm" :rules="rules" ref="addNewForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="addNewForm.title" placeholder="请输入新闻名称"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <v-md-editor v-model="addNewForm.content" height="400px" :disabled-menus="[]"
            @upload-image="handleUploadImage"></v-md-editor>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload class="image-uploader" action="/api/upload/image" :show-file-list="false"
            :on-success="handleAvatarSuccess1" :before-upload="beforeAvatarUpload">
            <img v-if="addNewForm.cover" :src="addNewForm.cover" class="image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="addNewForm.type" placeholder="请选择">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDialogVisible = false" style="width: 68px" size="medium">取消</el-button>
        <el-button type="primary" @click="addOneNew('addNewForm')" style="width: 68px" size="medium">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  adminGetArticles, deleteArticle, modifyArticle, createArticle, publishArticle
  , approveArticle, rejectArticle
} from '@/api/controller/4.news/index'
import { userGetAllCategory } from '@/api/controller/5.type/index'
import request from '@/utils/request';
export default {
  mounted() {
    this.getNew();
  },
  data() {
    let keyword = "";
    let NewList;
    let total = 0;
    let loading = false;
    let dialogVisible = false;
    let addDialogVisible = false;
    return {
      paramsForm: {
        pageSize: 10,
        pageNum: 1,
      },
      updateNewForm: {
        id: 0,
        title: "",
        content: "",
        cover: "",
        type: 0
      },
      addNewForm: {
        title: "",
        content: "",
        cover: "",
        type: null
      },
      rules: {
        title: [
          { required: true, message: '请输入新闻名称！', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入内容！', trigger: 'change' }
        ],
        cover: [
          { required: true, message: '请上传封面！', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择类型！', trigger: 'change' }
        ],
      },
      keyword,
      NewList,
      total,
      loading,
      dialogVisible,
      addDialogVisible,
      typeList: [],
      typePageForm: {
        pageNum: 1,
        pageSize: 20
      },
    };
  },
  methods: {
    indexMethod(index) {
      return (
        index + 1 + this.paramsForm.pageSize * (this.paramsForm.pageNum - 1)
      );
    },
    searchNew() {
      if (this.keyword === "") {
        this.$message.error("搜索关键词不能为空！");
      } else {
        this.paramsForm.key = this.keyword;
        this.getNew();
      }
    },
    refreshNew() {
      this.paramsForm.key = "";
      this.getNew();
    },
    async getNew() {
      this.loading = true;
      adminGetArticles(
        this.paramsForm.pageNum, this.paramsForm.pageSize
      )
        .then((response) => {
          const { data } = response;
          this.NewList = data.list;
          this.total = data.total;
        })
        .catch((error) => {
          this.$message.error(error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async deleteNew(id) {
      this.$confirm('此操作将永久删除该新闻, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticle(id)
          .then((response) => {
            const { message } = response;
            this.$message.success(message);
            this.getNew();
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async updateOneNew(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modifyArticle(this.updateNewForm)
            .then((response) => {
              const { message } = response;
              this.$message.success(message);
              this.getNew();
              this.dialogVisible = false;
            })
            .catch((error) => {
              this.$message.error(error.message);
            });
        } else {
          return false;
        }
      });
    },
    async addOneNew(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          createArticle(this.addNewForm)
            .then((response) => {
              const { message } = response;
              this.$message.success(message);
              this.getNew();
              this.addDialogVisible = false;
            })
            .catch((error) => {
              this.$message.error(error.message);
            });
        } else {
          return false;
        }
      });
    },
    async publishNew(data) {
      publishArticle(data)
        .then((response) => {
          const { message } = response;
          this.$message.success(message);
          this.getNew();
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    async passNew(id) {
      approveArticle(id)
        .then((response) => {
          const { message } = response;
          this.$message.success(message);
          this.getNew();
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    async failedNew(id) {
      rejectArticle(id)
        .then((response) => {
          const { message } = response;
          this.$message.success(message);
          this.getNew();
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    async getTypeList() {
      userGetAllCategory(this.typePageForm.pageNum, this.typePageForm.pageSize)
        .then((response) => {
          const { data } = response;
          this.typeList = data.list.filter(item => item.id >= 0)
        })
        .catch((error) => {
          this.$message.error(error.message);
        })
    },
    handleEdit(data) {
      Object.assign(this.updateNewForm, data);
      if (this.typeList.length == 0) this.getTypeList()
      this.dialogVisible = true;
    },
    handleAdd() {
      if (this.typeList.length == 0) this.getTypeList()
      this.addDialogVisible = true;
    },

    handleSizeChange(val) {
      this.paramsForm.pageSize = val;
      this.getNew();
    },
    handleCurrentChange(val) {
      this.paramsForm.pageNum = val;
      this.getNew();
    },
    handleAvatarSuccess(res) {
      this.updateNewForm.cover = res.data.imageUrl
    },
    handleAvatarSuccess1(res) {
      this.addNewForm.cover = res.data.imageUrl
    },
    beforeAvatarUpload(file) {
      let types = ['image/jpeg', 'image/jpg', 'image/png'];
      const isJPG = types.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 20

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、JPEG、PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
      }
      return isJPG && isLt2M;
    },
    handleUploadImage(_event, insertImage, files) {
      for (let i in files) {
        const formData = new FormData()
        formData.append('file', files[i])
        request.post(`/upload/image`, formData).then(
          (response) => {
            const { data } = response
            insertImage({
              url: data.imageUrl,
              desc: 'desc',
            })
          },
          (error) => {
            this.$message.error(error.message)
          },
        )
      }
    }
  },
};
</script>
<style scoped></style>
